//
//  ComplaintAdviceVC.m
//  homeland
//
//  Created by gzbugu on 14-8-8.
//  Copyright (c) 2014年 xzysun. All rights reserved.
//  社情及时报－
//

#import "ReportComplaintAdviceVC.h"
#import "MKNetworkKit.h"
#import "ConfigManage.h"
#import "ListViewController.h"
#import "UserInfoService.h"
#define INPUT_VIEW_OFFSET 100.0
@interface ReportComplaintAdviceVC ()

@end

@implementation ReportComplaintAdviceVC
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    if (self.config!=nil) {
        NSString *myValue=[self.config objectForKey:@"key"];
        self.title=myValue;
    }
    self.navigationItem.rightBarButtonItem = rightNavBtnWithImgName(@"我的上报", self, @selector(rightBtAction:));
    self.navigationItem.leftBarButtonItem = autoavBackButton(self, @selector(backMethod));
    self.txtTittle.inputAccessoryView = [self getInputAccessoryView];
    self.txtContent.inputAccessoryView = [self getInputAccessoryView];
    self.txtName.inputAccessoryView = [self getInputAccessoryView];
    self.txtPhone.inputAccessoryView = [self getInputAccessoryView];
    [_scrollView addSubview:_formPanelView];
    _scrollView.contentSize = _formPanelView.frame.size;
    self.title=@"社情及时报";
    self.txtName.delegate = self;
    self.txtName.tag = 1;
    self.txtPhone.delegate = self;
    self.txtPhone.tag = 2;
    UserInfoService *userInfo=[UserInfoService getUserInfoService];
    
    self.txtName.text = [CommonUtil dealNullObject:userInfo.userInfo.nickName];
    self.txtPhone.text = [CommonUtil dealNullObject:userInfo.userInfo.mobile];
    
    //元素添加边框
    //--------------------------
    self.txtContent.layer.borderWidth = 1;
    self.txtContent.layer.borderColor = [[UIColor blackColor] CGColor];
    self.txtContent.layer.cornerRadius = 0;
}

-(void)backMethod
{
    [DataStoreService deleteFromKeychain:COMPLAINTYPE];
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - Button Methods
-(void)rightBtAction:(id)sender{
    ListViewController *listVC = [[ListViewController alloc]initWithNibName:@"ListViewController" bundle:nil];
    NSDictionary *vcConfig =[NSDictionary dictionaryWithObjectsAndKeys:@"社情及时报-我的上报",@"key",nil];
    listVC.config=vcConfig;
    [self.navigationController pushViewController:listVC animated:YES];
}

-(IBAction)selectPhotoMethod:(id)sender{
    //在这里呼出下方菜单按钮项
    myActionSheet = [[UIActionSheet alloc]
                     initWithTitle:nil
                     delegate:self
                     cancelButtonTitle:@"取消"
                     destructiveButtonTitle:nil
                     otherButtonTitles: @"打开照相机", @"从手机相册获取",nil];
    
    [myActionSheet showInView:self.view];
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    //呼出的菜单按钮点击后的响应
    if (buttonIndex == myActionSheet.cancelButtonIndex){
        NSLog(@"取消");
    }
    switch (buttonIndex){
        case 0:  //打开照相机拍照
            [self takePhoto];
            break;
            
        case 1:  //打开本地相册
            [self LocalPhoto];
            break;
    }
}


//开始拍照
-(void)takePhoto{
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]){
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        //设置拍照后的图片可被编辑
        picker.allowsEditing = YES;
        picker.sourceType = sourceType;
        [self presentViewController:picker animated:YES completion:^{
        }];
    }else{
        NSLog(@"模拟其中无法打开照相机,请在真机中使用");
    }
}

//打开本地相册
-(void)LocalPhoto{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.delegate = self;
    //设置选择后的图片可被编辑
    picker.allowsEditing = YES;
    [self presentViewController:picker animated:YES completion:^{
        //
    }];
}

//当选择一张图片后进入这里
-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    //当选择的类型是图片
    if ([type isEqualToString:@"public.image"]){
        //先把图片转成NSData
        UIImage* image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        NSData *data;
        if (UIImagePNGRepresentation(image) == nil){
            data = UIImageJPEGRepresentation(image, 1.0);
        }else{
            data = UIImagePNGRepresentation(image);
        }
        
        //图片保存的路径
        //这里将图片放在沙盒的documents文件夹中
        NSString * DocumentsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
        
        
        //文件管理器
        NSFileManager *fileManager = [NSFileManager defaultManager];
        
        //把刚刚图片转换的data对象拷贝至沙盒中 并保存为image.png
        [fileManager createDirectoryAtPath:DocumentsPath withIntermediateDirectories:YES attributes:nil error:nil];
        [fileManager createFileAtPath:[DocumentsPath stringByAppendingString:@"/image.png"] contents:data attributes:nil];
        
        //得到选择后沙盒中图片的完整路径
        filePath = [[NSString alloc]initWithFormat:@"%@%@",DocumentsPath,  @"/image.png"];
        
        //关闭相册界面
        [picker dismissViewControllerAnimated:YES completion:^{
            //
        }];
        
        //创建一个选择后图片的小图标放在下方
        //类似微薄选择图后的效果
        //        UIImageView *smallimage = [[UIImageView alloc] initWithFrame:CGRectMake(50, 120, 40, 40)];
        
        self.imgViewSelect.image = image;
    }
    
}


- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:^{
        //
    }];
}

-(void)sendInfo{
    NSLog(@"图片的路径是：%@", filePath);
}

- (void)viewDidUnload{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//提交事件
-(IBAction)commitMethod:(id)sender{
    NSString *strTittle=[self.txtTittle text];
    NSString *strContent=[self.txtContent text];
    if (strTittle.length==0||strContent.length==0) {
        [self.view makeToast:@"请按照要求填写信息" duration:2.0 position:@"center"];
        return;
    }
    
    MKNetworkEngine *engine =nil;
    engine=[[MKNetworkEngine alloc] initWithHostName:SERVER_URL_COMPLAINT_ADVICE_ADD customHeaderFields:nil];
    
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    [dic setValue:strTittle forKey:@"title"];
    [dic setValue:strContent forKey:@"content"];
    UserInfoService *userInfo=[UserInfoService getUserInfoService];
    NSString *currentLoginUserName=@"";
    NSString *mobile=@"";
    if (userInfo.currentLoginUserName && userInfo.currentLoginUserName.length>0) {
        currentLoginUserName=userInfo.currentLoginUserName;
        mobile=userInfo.userInfo.mobile;
    }else{
        [dic setValue:getDeviceIdentifier() forKey:@"imeiCode"];//要加入的唯一标示
    }
    [dic setValue:userInfo.userInfo.Id forKey:@"userId"];
    [dic setValue:self.txtPhone.text forKey:@"phone"];
    [dic setValue:self.txtName.text forKey:@"name"];
    [dic setValue:getDeviceIdentifier() forKey:@"imsi_code"];//要加入的唯一标示
    [dic setValue:[CommonUtil dealNullObject:[_config objectForKey:@"streetId"]] forKey:@"streetId"];
    [dic setValue:[CommonUtil dealNullObject:[_config objectForKey:@"streetName"]] forKey:@"streetName"];
    [dic setValue:[CommonUtil dealNullObject:[_config objectForKey:@"communityId"]] forKey:@"communityId"];
    [dic setValue:[CommonUtil dealNullObject:[_config objectForKey:@"communityName"]] forKey:@"communityName"];
    [dic setValue:[CommonUtil dealNullObject:[_config objectForKey:@"partyMember"]] forKey:@"partyMember"];
    
    NSLog(@"提交的参数为：%@", dic);
    MKNetworkOperation *op = [engine operationWithPath:@"" params:dic httpMethod:@"POST"];
    if (filePath) {
        [op addFile:filePath forKey:@"media" mimeType:@"image/jpeg"];
    }
    [op addCompletionHandler:^(MKNetworkOperation *operation) {
        NSLog(@"[operation responseData]-->>%@", [operation responseString]);
        [self loadDataFinished];
    }errorHandler:^(MKNetworkOperation *errorOp, NSError* err) {
        NSLog(@"MKNetwork request error : %@", [err localizedDescription]);
        [self loadDataFaild:[err localizedDescription]];
    }];
    [engine enqueueOperation:op];
    [self startLoadingView];
}
-(void)startLoadingView{
    loadingView = [[MBProgressHUD alloc]initWithView:self.view];
    loadingView.labelText = @"正在提交...";
    [self.view addSubview:loadingView];
    [loadingView show:YES];
}
-(void)loadDataFinished{
    [loadingView removeFromSuperview];
    loadingView = nil;
    [self.view makeToast:@"上报成功" duration:2.0 position:@"center"];
}

-(void)loadDataFaild:(NSString *)msg{
    [loadingView removeFromSuperview];
    loadingView = nil;
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"错误" message:msg delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alert show];
}
///开始输入内容
-(void)textViewDidBeginEditing:(UITextView *)textView{
    textView.text=@"  ";
}

#pragma mark - Text Field Delegate
//开始输入的时候向上移动整个界面，这个输入框不会被挡住
-(void)textFieldDidBeginEditing:(UITextField *)textField{
    [UIView beginAnimations:@"animation" context:nil];
    [UIView setAnimationDuration:0.2f];
    CGRect frame = self.view.frame;
    frame.origin.y = frame.origin.y - INPUT_VIEW_OFFSET * textField.tag;
    self.view.frame = frame;
    [_scrollView scrollRectToVisible:CGRectMake(0, CGRectGetMinY(textField.frame), 320, 200) animated:NO];
    [UIView commitAnimations];
}

//输入结束的时候把整个界面向下移动，这个能恢复正常
-(void)textFieldDidEndEditing:(UITextField *)textField{
    [UIView beginAnimations:@"animation" context:nil];
    [UIView setAnimationDuration:0.2f];
    CGRect frame = self.view.frame;
    frame.origin.y = frame.origin.y + INPUT_VIEW_OFFSET * textField.tag;
    self.view.frame = frame;
    [UIView commitAnimations];
}
@end